//
//  UIColor+XAExtension.swift
//  XAPageViewDemo
//
//  Created by XangAm on 2017/12/30.
//  Copyright © 2017年 Lan. All rights reserved.
//

import UIKit

extension UIColor{
    
    static open var rondomColor : UIColor{
        let r = CGFloat(arc4random_uniform(256))
        let g = CGFloat(arc4random_uniform(256))
        let b = CGFloat(arc4random_uniform(256))
        
        return UIColor(r: r , g: g, b: b)
    }
    
    open var RGB : (CGFloat,CGFloat,CGFloat){
        
        var r : CGFloat = 0,g : CGFloat = 0,b : CGFloat = 0
        getRed(&r, green: &g, blue: &b, alpha: nil)
        
        return (r * 255,g * 255,b * 255)
    }
    
    
    convenience public init(r : CGFloat, g : CGFloat , b : CGFloat , alpha : CGFloat = 1){
        
        self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: alpha)
    }
    
    convenience public init?(hexColorString hexColor : String,alpha : CGFloat = 1){
        var hexColor = hexColor
        guard hexColor.count >= 6 else{
            return nil
        }
        
       
        if hexColor.count > 6{
             //判断前缀是否是##,0x,#
            var startSubIndex : String.Index? = nil
            if hexColor.hasPrefix("##") ||
                hexColor.hasPrefix("0x"){
                startSubIndex = hexColor.index(hexColor.startIndex, offsetBy: 2)
            }
            if hexColor.hasPrefix("#"){
                startSubIndex = hexColor.index(hexColor.startIndex, offsetBy: 1)
            }
            
            if let startSubIndex = startSubIndex {
                hexColor = String(hexColor.suffix(from: startSubIndex))
                hexColor =  hexColor.uppercased()
                
            }
        }
        //进行转换
        let rStr = (hexColor as NSString).substring(with: NSMakeRange(0, 2))
        let gStr = (hexColor as NSString).substring(with: NSMakeRange(2, 2))
        let bStr = (hexColor as NSString).substring(with: NSMakeRange(4, 2))
        
        var r : UInt32 = 0 ,g : UInt32 = 0,b : UInt32 = 0
        Scanner(string: rStr).scanHexInt32(&r)
        Scanner(string: gStr).scanHexInt32(&g)
        Scanner(string: bStr).scanHexInt32(&b)
//        self.init()
        self.init(r: CGFloat(r), g: CGFloat(g), b: CGFloat(b), alpha: alpha)
    }
    
    
    
    
}
